package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author 虎哥
 */
@Service
public class SpuDetailServiceImpl extends ServiceImpl<SpuDetailMapper, SpuDetail> implements SpuDetailService {
    private final SpuMapper spuMapper;
    private final SpecParamService paramService;

    public SpuDetailServiceImpl(SpuMapper spuMapper, SpecParamService paramService) {
        this.spuMapper = spuMapper;
        this.paramService = paramService;
    }

    @Override
    public List<SpecParamDTO> querySpecValues(Long id, Boolean searching) {
        // 1.查询当前商品信息，获取商品分类信息
        Spu spu = spuMapper.selectById(id);
        Long cid3 = spu.getCid3();
        // 2.查询SpecParam，规格参数的key
        List<SpecParamDTO> params = paramService.queryParams(null, cid3, searching);

        // 3.查询SpuDetail，规格参数的值
        SpuDetail detail = getById(id);
        // 3.1.取出规格参数json值
        String json = detail.getSpecification();
        // 3.2.把json转为Map格式，方便根据param的id寻找对应的值
        Map<Long, Object> map = JsonUtils.toMap(json, Long.class, Object.class);

        // 4.把参数值与SpecParam配对，把值写入SpecParam
        for (SpecParamDTO param : params) {
            // 根据param的id去map中获取对应的值
            Object value = map.get(param.getId());
            // 把value写入param
            param.setValue(value);
        }
        return params;
    }
}
